package com.handler;

import com.message.ChatGroupCreateMessage;
import com.message.resp.ChatGroupCreateResp;
import com.session.ChatServerContext;
import com.session.ChatServerContextFactory;
import com.session.GroupChatServerFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Map;

/**
 * 创建群聊处理器
 */
@ChannelHandler.Sharable
public class CreateGroupChatHandler extends SimpleChannelInboundHandler<ChatGroupCreateMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatGroupCreateMessage msg) throws Exception {
//                                          1、获取当前在线用户的 channel 上下文
        ChatServerContext chatServerContext = ChatServerContextFactory.getInstance();

        //   2、 获取创建群聊涉及到用户各自的 channel
        Map<String, Channel> userNameMappingChannelMap = chatServerContext.getUserNameMappingChannelMapByBatchUserNames(msg.getInitGroupMembers());

        // 3、创建群聊
        GroupChatServerFactory.getInstance().createGroupChat(msg.getGroupName(), userNameMappingChannelMap.keySet());

        ChatGroupCreateResp chatGroupCreateResp = new ChatGroupCreateResp(
                chatServerContext.getUserNameByChannel(ctx.channel()),
                userNameMappingChannelMap.keySet(),
                msg.getGroupName());

        // 4、向组内成员发送已被拉入群聊的消息
        userNameMappingChannelMap.forEach((String key,Channel memberChannel) -> memberChannel.writeAndFlush(chatGroupCreateResp));

        ctx.fireChannelRead(msg);
    }
}
